package com.snow.datasource.intercept;

import com.snow.datasource.datasource.DynamicDataSourceContextHolder;
import com.snow.datasource.healths.MasterSlaveHealth;
import com.snow.datasource.properties.SnowFlakeProperties;
import com.snow.datasource.strategy.IStrategy;
import com.snow.datasource.strategy.manage.ManageStrategy;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.util.Properties;

/**
 * sql 拦截切换数据源
 *
 * @Description
 * @Author fanxl
 * @Date 2020/12/23
 **/
@Intercepts({
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
@Slf4j
public class MasterSlaveInterceptor implements Interceptor {
    @Autowired
    private SnowFlakeProperties snowFlakeProperties;
    @Autowired
    private ManageStrategy manageStrategy;
    @Autowired
    private MasterSlaveHealth masterSlaveHealth;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];

        boolean empty = true;
        try {
            empty = StringUtils.isEmpty(DynamicDataSourceContextHolder.peek());
            if (empty) {
                String dbKey = getDataSource(ms);
                if (masterSlaveHealth.getDbHealth().containsKey(dbKey)) {
                    DynamicDataSourceContextHolder.push(dbKey);
                } else {
                    DynamicDataSourceContextHolder.push(snowFlakeProperties.getPrimary());
                }
            }
            return invocation.proceed();
        } finally {
            if (empty) {
                DynamicDataSourceContextHolder.clear();
            }
        }
    }

    public String getDataSource(MappedStatement mappedStatement) {
        if (SqlCommandType.SELECT == mappedStatement.getSqlCommandType()) {
            return manageStrategy.handle();
        }
        return snowFlakeProperties.getPrimary();
    }

    @Override
    public Object plugin(Object target) {
        return target instanceof Executor ? Plugin.wrap(target, this) : target;
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
